package com.sifang.bussiness.merchant.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.sifang.base.util.MchHttpUtil;
import com.sifang.bussiness.dao.order.MerchantDao;
import com.sifang.bussiness.dao.order.PayDao;
import com.sifang.bussiness.dao.table.merchant.MpMerchant;
import com.sifang.bussiness.dao.table.order.MpPay;
import com.sifang.bussiness.dao.withdrawal.WithdrawalDao;
import com.sifang.bussiness.merchant.bean.MerchantReqNotify;
import com.sifang.bussiness.merchant.service.MerchantNotifyService;


@Service("MerchantNotifyService")
public class MerchantNotifyServiceImpl implements MerchantNotifyService {
	
	private static Logger log = LoggerFactory.getLogger(MerchantNotifyServiceImpl.class);
	
	@Autowired
	PayDao payDao;
	
	@Autowired
	WithdrawalDao withdrawalDao;
	
	@Autowired
	MerchantDao merchantDao;

	@Async
	@Override
	public void payNotifySync(MpPay pay) {
		//MpPay pay = payDao.getOrderByCode(code);
		/*
		 * if(null == pay) { log.info("异步 通知订单不存在或订单状态未更新。平台订单号:{}",code); return; }else
		 */if(pay.getStatus()<MpPay.STATUS_PAY_FAIL) {
			log.error("异步 通知订单不存在或订单状态未更新。平台订单号:{}，订单状态：{}",pay.getCode(),pay.getStatus());
			log.info("异步 通知订单不存在或订单状态未更新。平台订单号:{}，订单状态：{}",pay.getCode(),pay.getStatus());
			return;
		}
		
		MpMerchant mpMerchant = merchantDao.getMerchantByCode(pay.getMerchant_code());
		//根据订单信息通知商户
		if(null != pay) {
			if(null != pay.getCallback_url() && !pay.getCallback_url().equals("")) {
				//封装报文通知商户
				MerchantReqNotify merchantReqNotify = new MerchantReqNotify();
				merchantReqNotify.setBody(pay.getGoods());
				merchantReqNotify.setFinish_time(pay.getEnd().getTime()+"");
				merchantReqNotify.setMch_id(pay.getMerchant_code());
				merchantReqNotify.setOrder_date(pay.getBegin().getTime()+"");
				merchantReqNotify.setOrder_sn(pay.getCode());
				merchantReqNotify.setOut_trade_no(pay.getCh_code());
				merchantReqNotify.setService(pay.getPay_kind_code());
				if(pay.getStatus() == MpPay.STATUS_PAY_SUCCESS) {
					merchantReqNotify.setStatus(1);
				}else {
					merchantReqNotify.setStatus(0);
				}
				merchantReqNotify.setTime_expire(pay.getExpires().getTime()+"");
				merchantReqNotify.setTime_start(pay.getBegin().getTime()+"");
				merchantReqNotify.setTotal_fee(pay.getFee());
				int status = getSendMchCallbackStatus(merchantReqNotify,mpMerchant.getSecret_key(),pay.getCallback_url());
				log.info("通知商户状态#:{}",status);
				//更新通知状态
				if(status == MchHttpUtil.SEND_STATUS_SUCCESS) {
					int result = payDao.updatePayMerchantNotifyStatusByCode(pay.getCode(), 1);
					log.info("1更新通知状态结果：{}",result);
				}else if(status == MchHttpUtil.SEND_STATUS_FAIL) {
					int result = payDao.updatePayMerchantNotifyStatusByCode(pay.getCode(), 0);
					log.info("2更新通知状态结果：{}",result);
				}else if(status == MchHttpUtil.SEND_STATUS_TIME_OUT) {
					int result = payDao.updatePayMerchantNotifyStatusByCode(pay.getCode(), 0);
					log.info("3更新通知状态结果：{}",result);
				}
			}
		}
		
	}
	
	@Override
	public int payNotify(MpPay pay) {
		MpMerchant mpMerchant = merchantDao.getMerchantByCode(pay.getMerchant_code());
		//根据订单信息通知商户
		if(null != pay.getCallback_url() && !pay.getCallback_url().equals("")) {
			//封装报文通知商户
			MerchantReqNotify merchantReqNotify = new MerchantReqNotify();
			merchantReqNotify.setBody(pay.getGoods());
			merchantReqNotify.setFinish_time(pay.getEnd().getTime()+"");
			merchantReqNotify.setMch_id(pay.getMerchant_code());
			merchantReqNotify.setOrder_date(pay.getBegin().getTime()+"");
			merchantReqNotify.setOrder_sn(pay.getCode());
			merchantReqNotify.setOut_trade_no(pay.getCh_code());
			merchantReqNotify.setService(pay.getPay_kind_code());
			if(pay.getStatus() == MpPay.STATUS_PAY_SUCCESS) {
				merchantReqNotify.setStatus(1);
			}else {
				merchantReqNotify.setStatus(0);
			}
			merchantReqNotify.setTime_expire(pay.getExpires().getTime()+"");
			merchantReqNotify.setTime_start(pay.getBegin().getTime()+"");
			merchantReqNotify.setTotal_fee(pay.getFee());
			int status = getSendMchCallbackStatus(merchantReqNotify,mpMerchant.getSecret_key(),pay.getCallback_url());
			log.info("通知商户状态*:{}",status);
			//更新通知状态
			if(status == MchHttpUtil.SEND_STATUS_SUCCESS) {
				int result = payDao.updatePayMerchantNotifyStatusByCode(pay.getCode(), 1);
				log.info("1更新通知状态结果：{}",result);
			}else if(status == MchHttpUtil.SEND_STATUS_FAIL) {
				int result = payDao.updatePayMerchantNotifyStatusByCode(pay.getCode(), 0);
				log.info("2更新通知状态结果：{}",result);
			}else if(status == MchHttpUtil.SEND_STATUS_TIME_OUT) {
				int result = payDao.updatePayMerchantNotifyStatusByCode(pay.getCode(), 0);
				log.info("3更新通知状态结果：{}",result);
			}
			return status;
		}
		return MchHttpUtil.SEND_STATUS_FAIL;
	}
	
	
	@HystrixCommand(commandKey = "pay003", 
			groupKey = "payGroup",
			fallbackMethod = "getSendMchCallbackStatusTimeOutFallBack",
			ignoreExceptions = {Exception.class},
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.strategy",value = "THREAD"),
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "6000" )//6秒超时
            })
	public int getSendMchCallbackStatus(MerchantReqNotify merchantReqNotify, String key, String url) {
		return MchHttpUtil.sendMchCallBack(merchantReqNotify,key,url);
	}
	
	
	public int getSendMchCallbackStatusTimeOutFallBack(MerchantReqNotify merchantReqNotify, String key, String url) {
		return MchHttpUtil.SEND_STATUS_TIME_OUT;
	}
	

	@Async
	@Override
	public void withDrawalCallBackNotify(String code) {
		//Withdrawal withdrawal = withdrewDao.getWithDrawalByCode(code);
		//根据订单信息通知商户
		
	}

}
